package com.lhd.egweibo3.controller;

import com.lhd.egweibo3.common.response.JsonResult;
import com.lhd.egweibo3.common.response.StatusCode;
import com.lhd.egweibo3.mapper.UserMapper;
import com.lhd.egweibo3.pojo.dto.UserLoginDTO;
import com.lhd.egweibo3.pojo.dto.UserRegDTO;
import com.lhd.egweibo3.pojo.entity.User;
import com.lhd.egweibo3.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author lhd
 * @date 2024/4/25
 * @apiNote
 */
@Api(tags = "1.用户模块")
@Slf4j
@RestController
@RequestMapping(value ="v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @PostMapping(value ="reg")
    @ApiOperation(value = "用户注册")
    public JsonResult register(@RequestBody UserRegDTO userRegDTO){
        log.debug("userRegDTO{}",userRegDTO);

        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO != null){
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXIST);
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);

        return JsonResult.ok();
    }

    @PostMapping(value ="login")
    @ApiOperation("登录功能")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("userRegDTO{}",userLoginDTO);

        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        //查验用户名是否正确
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }

        if (userLoginDTO.getPassword().equals(userVO.getPassword())){
            session.setAttribute("user", userVO);
            return JsonResult.ok(StatusCode.LOGIN_SUCCESS);
        }

        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }
    /**
     * 获取当前用户
     */
    @ApiOperation("获取当前用户")
    @GetMapping(value = "currentUser")
    public JsonResult getCurrentUser(@ApiIgnore HttpSession session){
        log.debug("session{}",session);
        UserVO userVO = (UserVO)session.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    /**
     * 退出登录
     */
    @ApiOperation("退出登录")
    @GetMapping(value ="logout")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }


}
